package com.alphacsp.theedge2012.data.service;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import com.alphacsp.theedge2012.data.database.DataAccessor;

/**
 * Created by IntelliJ IDEA.
 * User: Gilad
 * Date: 06/11/10
 * Time: 16:03
 */
public class NetworkService extends IntentService {

    public static final String STATUS_LISTENER = "status_receiver";

    public static final String REFRESH_ACTION = "refresh_action";
    public static final int REFRESH_SPEAKERS = 1;

    public static final int REFRESH_SESSIONS = 2;
    public static final int REFRESH_SCHEDULE = 3;
    public static final int REFRESH_ALL = 4;
    public static final int STATUS_REFRESHED = 5;

    public static final int STATUS_NOT_REFRESHED = 6;

    public NetworkService() {
        super(NetworkService.class.getName());
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        final DataAccessor dataAccessor = DataAccessor.getSingleton(this);

        final ResultReceiver receiver = intent.getParcelableExtra(STATUS_LISTENER);
        final int requestAction = intent.getIntExtra(REFRESH_ACTION, -1);
        boolean result = false;

        if (requestAction == REFRESH_SPEAKERS) {
            result = dataAccessor.syncAllSpeakers();
        } else if (requestAction == REFRESH_SESSIONS) {
            result = dataAccessor.syncAllSessions();
        } else if (requestAction == REFRESH_SCHEDULE) {
            result = dataAccessor.syncAllEvents();
        } else if (requestAction == REFRESH_ALL) {
            dataAccessor.syncAllSpeakers();
            dataAccessor.syncAllSessions();
            dataAccessor.syncAllEvents();
        }
        if (result) {
            receiver.send(STATUS_REFRESHED, Bundle.EMPTY);
        }
        receiver.send(STATUS_NOT_REFRESHED, Bundle.EMPTY);

    }
}
